package com.peanut.baby.config;

import android.content.Context;
import android.content.SharedPreferences;

import com.peanut.baby.InitManager;
import com.peanut.baby.http.BaseObserver;
import com.peanut.baby.http.BaseScheduler;
import com.peanut.baby.http.RetrofitClient;
import com.peanut.baby.model.ConfigParam;

import io.reactivex.Observable;

/**
 * Created by anonymouslystudio on 2017/8/23.
 */

public class ConfigParamsManager {
    private static final String CONFIG_PREF_NAME = "configParams";
    private SharedPreferences prefs;
    private static ConfigParamsManager _instance;
    private ConfigParamsManager(){

    }

    public static ConfigParamsManager getInstance(){
        if(_instance == null){
            synchronized (ConfigParamsManager.class){
                if(_instance == null){
                    _instance = new ConfigParamsManager();
                }
            }
        }
        return _instance;
    }

    public void updateAllConfigs(){
        updateServiceMobile();
    }

    public String getServiceMobile(){
        String prefName = getPrefName(ConfigParam.ID_SERVICE_CONTACT);
        return getPrefs().getString(prefName,"");
    }

    private void updateServiceMobile(){
        Observable obs = RetrofitClient.getInstance().getConfigParam(ConfigParam.ID_SERVICE_CONTACT);
        obs.compose(BaseScheduler.<String>compose()).subscribe(new BaseObserver<String>() {
            @Override
            protected void onHandleSuccess(String o) {
                saveParams(getPrefName(ConfigParam.ID_SERVICE_CONTACT),o);
            }

            @Override
            protected void onHandleError(String code,String msg) {

            }
        });
    }

    private String getPrefName(int configId){
        return "config_params_"+configId;
    }

    private SharedPreferences getPrefs(){
        if(prefs == null){
            prefs = InitManager.getInstance().getCtx().getSharedPreferences(CONFIG_PREF_NAME, Context.MODE_PRIVATE);
        }
        return prefs;
    }

    private void saveParams(String prefName,String value){
        getPrefs().edit().putString(prefName,value).commit();
    }
}
